package com.joint.web.action.com;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.joint.base.entity.*;
import com.joint.base.service.DepartmentService;
import com.joint.base.service.DutyService;
import com.joint.base.service.PostService;
import com.joint.base.service.PowerService;
import com.joint.base.util.DataUtil;
import com.joint.web.action.BaseAdminAction;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by gcw on 2015/1/13.
 */
@ParentPackage("com")
public class AjaxPowerAction extends BaseAdminAction {
    @Resource
    private PowerService powerService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private PostService postService;
    @Resource
    private DutyService dutyService;

    protected Power power;
    private String no;
    private String name;
    private String description;
    private String d_id;
    private String p_id;
    private String parentId;
    private String rowIds;
    private String powerName;
    private List<Map<String,Object>> powerArrayList;

    public List<Map<String,Object>> dArrayList;

    /**
     * 党政模块定义的属性
     */
    private String departId;
    private String usersId;
    private String powerId;

    /**
     * 党政模块定义的方法
     * @return
     */
    public String powerByDepartAndUsers(){
        Company company=usersService.getCompanyByUser();
        pager = new Pager();
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.asc);
        Map<String,Object> params=new HashMap<String,Object>();
        params.put("company",company);
        params.put("state",BaseEnum.StateEnum.Enable);
        Department department=new Department();
        Set<Duty> dutySet= Sets.newHashSet();
        List<String> idsList=Lists.newArrayList();
        List<Power> powerList1=Lists.newArrayList();
        Users users=new Users();
        if(StringUtils.isNotEmpty(usersId)){
            users=usersService.get(usersId);
        }
        if(StringUtils.isNotEmpty(departId)){
            department=departmentService.get(departId);
        }

        if(StringUtils.isNotEmpty(powerId)){
            for(String s:powerId.split(",")){
                    powerList1.add(powerService.get(s.trim()));
            }
        }
        dutySet=users.getDutySet();
        for(Duty duty:dutySet){
            if(duty.getDepartment()==department){
                idsList.add(duty.getPower().getId());
            }
        }
        params.put("id",idsList);


        pager = powerService.findByPagerAndCompany(pager, null, company, params);
        List<Power> powerList = (List<Power>) pager.getList();
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        if(powerList1.size()>0){
            if(powerList.removeAll(powerList1)) {
                for(Power powers:powerList) {
                    LogUtil.info("power_1"+powers.getName());
                    rMap=new HashMap<String, Object>();
                    rMap.put("id",powers.getId());
                    rMap.put("user",users.getName());
                    rMap.put("department",powers.getDepartment()!=null?powers.getDepartment().getName():"");
                    rMap.put("power",powers.getName()!=null?powers.getName():"");
                    dataRows.add(JSONObject.fromObject(rMap));
                }
            }else{
                for(Power power:powerList1){
                    LogUtil.info("power_3"+power.getName());
                }

            }
        }else{
            for(Power powers:powerList) {
                LogUtil.info("power_2"+powers.getName());
                rMap=new HashMap<String, Object>();
                rMap=new HashMap<String, Object>();
                rMap.put("id",powers.getId());
                rMap.put("user",users.getName());
                rMap.put("department",powers.getDepartment()!=null?powers.getDepartment().getName():"");
                rMap.put("power",powers.getName()!=null?powers.getName():"");
                dataRows.add(JSONObject.fromObject(rMap));
            }
        }
        long total =pager.getTotalCount();
        if(total%rows==0){
            total = total/rows;
        }else{
            if(total<rows){
                total = 1;
            }else{
                total = total/rows + 1;
            }
        }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        data.put("total",total);
        data.put("records",pager.getTotalCount());
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }


    /**
     * 根据查询项加载JqGrid里的数据
     * @param _search
     * @param params
     * @param filters
     * @return
     */
    public Map getSearchFilterParams(String _search,Map<String,Object> params,String filters){
        //createAlias Key集合
        List<String> alias = new ArrayList<String>();
        if(org.apache.commons.lang3.StringUtils.isNotEmpty(_search)){
            boolean __search = Boolean.parseBoolean(_search);
            if(__search&& org.apache.commons.lang3.StringUtils.isNotEmpty(filters)){
                JSONObject filtersJson = JSONObject.fromObject(filters);
                if(org.apache.commons.lang3.StringUtils.equals(filtersJson.getString("groupOp"), "AND")){
                    //查询条件
                    JSONArray rulesJsons = filtersJson.getJSONArray("rules");
                    //遍历条件
                    for(int i=0;i<rulesJsons.size();i++){
                        JSONObject rule = rulesJsons.getJSONObject(i);
                        if(rule.has("field")&& org.apache.commons.lang3.StringUtils.isNotEmpty(rule.getString("field"))&&rule.has("data")&& org.apache.commons.lang3.StringUtils.isNotEmpty(rule.getString("data"))){
                            String field = rule.getString("field");
                            if(field.contains("_")){
                                String[] fields = field.split("_");
                                if(org.apache.commons.lang3.StringUtils.isNotEmpty(rule.getString("data"))){
                                    params.put(field.replaceAll("_", "."), rule.getString("data"));
                                }
                            }else{
                                if(org.apache.commons.lang3.StringUtils.isNotEmpty(rule.getString("data"))){
                                    if(field.equals("createDate")){
                                        params.put("createDate", DataUtil.StringToDate(rule.getString("data")));
                                    }else if(field.equals("name")){
                                        params.put("department.name", rule.getString("data"));
                                    }else if(field.equals("upParent")){
                                      //  params.put("department.parent.name", rule.getString("data"));
                                    }else {
                                        params.put(field, rule.getString("data"));
                                    }
                                }
                            }
                        }
                    }

                }
            }
        }

        return params;
    }
    public String list(){
        Company company=usersService.getCompanyByUser();
        pager = new Pager(0);
       // pager.setPageSize(rows);
      //  pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.asc);
        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("state", new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
       // params = getSearchFilterParams(_search,params,filters);
        pager = powerService.findByPagerAndCompany(pager, null, company,params);
        List<Power> PowerList = (List<Power>) pager.getList();
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(Power powers:PowerList){
            rMap=new HashMap<String, Object>();
            rMap.put("id",powers.getId());
            rMap.put("description",powers.getDescription());
            if(powers.getDepartment()!=null && powers.getPost()!=null){
                rMap.put("name",powers.getDepartment().getName()+"-"+powers.getPost().getName());
            }
            if(powers.getParent()!=null){
                if(powers.getParent().getDepartment()!=null && powers.getParent().getPost()!=null){
                    rMap.put("upParent",powers.getParent().getDepartment().getName()+"-"+powers.getParent().getPost().getName());
                }else{
                    rMap.put("upParent", "");
                }
            }else{
                rMap.put("upParent","");
            }
            dataRows.add(JSONObject.fromObject(rMap));
        }
        long total =pager.getTotalCount();
        if(total%rows==0){
            total = total/rows;
        }else{
            if(total<rows){
                total = 1;
            }else{
                total = total/rows + 1;
            }
        }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        data.put("total",total);
        data.put("records",pager.getTotalCount());
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String save(){
        if(StringUtils.isNotEmpty(keyId)){
            power=powerService.get(keyId);
        }else{
            power=new Power();
        }
        power.setState(BaseEnum.StateEnum.Enable);
        power.setNo(no);
        power.setCompany(usersService.getCompanyByUser());
        power.setDescription(description);
        if(StringUtils.isNotEmpty(d_id)){
            Department dep = departmentService.get(d_id);
            power.setDepartment(dep);
            powerName = dep.getName();
        }
        if(StringUtils.isNotEmpty(p_id)){
            Post post = postService.get(p_id);
            power.setPost(post);
            powerName = powerName + "-" + post.getName();
            power.setName(powerName);
        }

        //if(StringUtils.isNotEmpty(parentId)){
        power.setParent(powerService.get(parentId));
       // }
        if(StringUtils.isNotEmpty(keyId)){
            powerService.update(power);
        }else{
            power.setName(powerName);
            powerService.save(power);
        }
        return ajaxHtmlCallback("200", "提交成功！","操作状态");
    }

    //职权信息
    public String configView(){
        Company company=usersService.getCompanyByUser();
        if(StringUtils.isNotEmpty(keyId)){
            power=powerService.get(keyId);
        }
        Pager dpager= new Pager(0);
        dpager=departmentService.findByPagerAndCompany(pager, null, company, new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
        Pager ppager= new Pager(0);
        ppager=postService.findByPagerAndCompany(pager, null, company, new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
        List<Department> departmentList= (List<Department>) dpager.getList();
        List<Post> postList= (List<Post>) ppager.getList();
        dArrayList=new ArrayList<Map<String, Object>>();
        Map<String,Object> rMap;
        for(Department department:departmentList){
            rMap=new HashMap<String, Object>();
            rMap.put("id",department.getId());
            rMap.put("name",department.getName());
            rMap.put("checked","");
            if(power!=null && power.getDepartment()!=null && department.getId().equals(power.getDepartment().getId())){
                rMap.put("checked","checked");
            }
            dArrayList.add(rMap);
        }
        return "configView";
    }

    public String input(){
        Company company=usersService.getCompanyByUser();
        if(StringUtils.isNotEmpty(keyId)){
            power=powerService.get(keyId);
        }
        Pager powerpager= new Pager(0);
        powerpager=powerService.findByPagerAndCompany(pager, null, company, new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
        List<Power> powerList= (List<Power>) powerpager.getList();
        powerArrayList=new ArrayList<Map<String, Object>>();
        Map<String,Object> rmap;
        for (Power powers:powerList){
            rmap=new HashMap<String, Object>();
            rmap.put("id",powers.getId());
            rmap.put("name",powers.getName());
            rmap.put("selected","");
            if(power!=null && powers.getParent()!=null && power.getParent()!=null && power.getParent().getId().equals(powers.getParent().getId())){
                rmap.put("selected","selected");
            }
            powerArrayList.add(rmap);
        }
        return "input";
    }

    //设置默认职权
    public String setPowerDefault(){
        if(StringUtils.isNotEmpty(keyId)){
            String departId=keyId.split("-")[0];
            String postId=keyId.split("-")[1];
            Department department=departmentService.get(departId);
            Map dmap = new HashMap<String,Object>();
            dmap.put("department", department);
            dmap.put("powerDefault", 1);
            List<Power> powers = powerService.getList(dmap);
            for(Power info: powers){
                if(!info.getId().equals(keyId)){
                    info.setPowerDefault(0);
                    powerService.update(info);
                }
            }
            Post post=postService.get(postId);
            power=powerService.getPowerByDepartAndPost(department,post);
            if(power.getPowerDefault()==1){
                power.setPowerDefault(0);
            }
            else{
                power.setPowerDefault(1);
            }
            powerService.update(power);
        }
        return ajaxHtmlCallback("200", "设置成功！","操作状态");
    }

    /**
     *职权zTree
     */
    public String zTree(){
        Company company=usersService.getCompanyByUser();
        Pager pager = new Pager(0);
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        //pager.setOrderBy("no");
        pager.setOrderType(BaseEnum.OrderType.asc);
        pager=powerService.findByPagerAndCompany(pager, null, company, new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
        List<Power> powerList=(List<Power>) pager.getList();
        List<JSONObject> treeList = new ArrayList<JSONObject>();
        for(Power per : powerList){
            Map<String,Object> rMap = new HashMap<String, Object>();
            rMap.put("id",per.getId());
            rMap.put("pId",per.getParent()==null?"":per.getParent().getId());
            rMap.put("pName",per.getDepartment().getName()+ "-" + per.getPost().getName());
            rMap.put("sName",per.getDepartment().getName()+ "-" + per.getPost().getName());
            rMap.put("name",per.getDepartment().getName()+ "-" + per.getPost().getName());
            rMap.put("open", false);
            treeList.add(JSONObject.fromObject(rMap));
        }
        Map<String, Object> data = new HashMap<String, Object>();
        data = new HashMap<String, Object>();
        data.put("data", JSONArray.fromObject(treeList));

        return ajaxHtmlAppResult(1, "", JSONObject.fromObject(data));
    }


    /**
     * 删除职权
     * @return
     */
    public String delete(){
        if(StringUtils.isEmpty(keyId)){
            return ajaxHtmlCallback("200", "请选择职权！","操作状态");
        }
        Power power = powerService.get(keyId);
        Set<Power> powers = power.getChildren();
        for(Power power1:powers){
            if(power1.getState().toString().equals("Enable")){
                return  ajaxHtmlCallback("400","该职权有下级职权,请先删除或修改","操作状态");
            }
        }
        List<Duty> dutys = dutyService.findByPower(power);
        for(Duty duty:dutys){
            duty.setState(BaseEnum.StateEnum.Delete);
            dutyService.update(duty);
        }
        powerService.delConfigPower(keyId);
        powerService.delRolePower(keyId);
        power.setState(BaseEnum.StateEnum.Delete);
        powerService.update(power);
        return ajaxHtmlCallback("200", "保存成功！","操作状态");
    }
    public Power getPower() {
        return power;
    }

    public void setPower(Power power) {
        this.power = power;
    }

    public String getNo() {
        return no;
    }

    public void setNo(String no) {
        this.no = no;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }


    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }


    public String getParentId() {
        return parentId;
    }

    public void setParentId(String parentId) {
        this.parentId = parentId;
    }

    public List<Map<String, Object>> getdArrayList() {
        return dArrayList;
    }

    public void setdArrayList(List<Map<String, Object>> dArrayList) {
        this.dArrayList = dArrayList;
    }

    public String getRowIds() {
        return rowIds;
    }

    public void setRowIds(String rowIds) {
        this.rowIds = rowIds;
    }

    public String getD_id() {
        return d_id;
    }

    public void setD_id(String d_id) {
        this.d_id = d_id;
    }

    public String getP_id() {
        return p_id;
    }

    public void setP_id(String p_id) {
        this.p_id = p_id;
    }

    public List<Map<String, Object>> getPowerArrayList() {
        return powerArrayList;
    }

    public void setPowerArrayList(List<Map<String, Object>> powerArrayList) {
        this.powerArrayList = powerArrayList;
    }

    public String getPowerName() {
        return powerName;
    }

    public void setPowerName(String powerName) {
        this.powerName = powerName;
    }

    public String getDepartId() {
        return departId;
    }

    public void setDepartId(String departId) {
        this.departId = departId;
    }

    public String getUsersId() {
        return usersId;
    }

    public void setUsersId(String usersId) {
        this.usersId = usersId;
    }

    public String getPowerId() {
        return powerId;
    }

    public void setPowerId(String powerId) {
        this.powerId = powerId;
    }
}

